package com.dingding.gmall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingding.gmall.common.dto.MemberDTO;
import com.dingding.gmall.common.dto.mq.order.OrderInfoDTO;
import com.dingding.gmall.common.exception.NoStockException;
import com.dingding.gmall.common.utils.PageUtils;
import com.dingding.gmall.common.utils.Query;
import com.dingding.gmall.common.utils.R;
import com.dingding.gmall.order.command.SubmitOrderCommand;
import com.dingding.gmall.order.constant.OrderConstant;
import com.dingding.gmall.order.constant.OrderStatusEnum;
import com.dingding.gmall.order.dao.OrderDao;
import com.dingding.gmall.order.dto.*;
import com.dingding.gmall.order.entity.OrderEntity;
import com.dingding.gmall.order.entity.OrderItemEntity;
import com.dingding.gmall.order.entity.PaymentInfoEntity;
import com.dingding.gmall.order.feign.CartFeignService;
import com.dingding.gmall.order.feign.MemberFeignService;
import com.dingding.gmall.order.feign.ProductFeignService;
import com.dingding.gmall.order.feign.WmsFeignService;
import com.dingding.gmall.order.interceptor.LoginInterceptor;
import com.dingding.gmall.order.service.OrderItemService;
import com.dingding.gmall.order.service.OrderService;
import com.dingding.gmall.order.service.PaymentInfoService;
import com.dingding.gmall.order.vo.MemberAddressVO;
import com.dingding.gmall.order.vo.OrderTradeVO;
import com.dingding.gmall.order.vo.PayAsyncVo;
import com.dingding.gmall.order.vo.SubmitOrderResponseVO;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<SubmitOrderCommand> submitOrderCommandThreadLocal = new ThreadLocal<>();

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WmsFeignService wmsFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    @Override
    public OrderTradeVO tradeOrder() {
        MemberDTO memberDTO = LoginInterceptor.memberDTOThreadLocal.get();
        OrderTradeVO orderTradeVO = new OrderTradeVO();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //1 、查询收货地址列表
            //将主线程的cookie放到新开的线程中
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVO> address = memberFeignService.getAddress(memberDTO.getId());
            orderTradeVO.setMemberAddressVOList(address);
        }, executor);
        CompletableFuture<Void> checkedCartItemsFuture = CompletableFuture.runAsync(() -> {
            //2、查询购物车选中的购物项
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemDTO> checkedCartItems = cartFeignService.getCheckedCartItems();
            orderTradeVO.setOrderItemDTOList(checkedCartItems);
            //3、查询用户积分
            //暂时写死
            memberDTO.setIntegration(101);
            Integer integration = memberDTO.getIntegration();
            orderTradeVO.setIntegralReducePrice(orderTradeVO.calculateIntegralReducePrice(integration));
            //订单总额
            orderTradeVO.setOrderPrice(orderTradeVO.getOrderPrice());
            //4、实际支付价格
            orderTradeVO.setActuallyPaidPrice(orderTradeVO.getActuallyPaidPrice());
            //5、商品总件数
            orderTradeVO.setGoodsCount(orderTradeVO.getGoodsCount());
        }, executor).thenRunAsync(() -> {
            //查询是否有库存
            List<OrderItemDTO> orderItemDTOList = orderTradeVO.getOrderItemDTOList();
            if (CollectionUtils.isNotEmpty(orderItemDTOList)) {
                List<Long> collect = orderItemDTOList.stream().map(OrderItemDTO::getSkuId).collect(Collectors.toList());
                R r = wmsFeignService.getSkusHasStock(collect);

                List<SkuHasStockDTO> data = r.getData(new TypeReference<List<SkuHasStockDTO>>() {});
                if (CollectionUtils.isNotEmpty(data)) {
                    Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuHasStockDTO::getSkuId, SkuHasStockDTO::getHasStock));
                    if (CollectionUtils.isEmpty(map)){
                        orderTradeVO.setStocks(Maps.newHashMap());
                    }
                    orderTradeVO.setStocks(map);
                }
            }
        }, executor);
        //7、防重令牌
        String uuid = UUID.randomUUID().toString().replace("-", "");
        orderTradeVO.setOrderToken(uuid);
        String orderToken = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberDTO.getId();
        redisTemplate.opsForValue().set(orderToken, uuid, 30, TimeUnit.SECONDS);
        try {
            CompletableFuture.allOf(getAddressFuture, checkedCartItemsFuture).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            log.info("结算订单异步任务出错");
        }
        return orderTradeVO;
    }

    @Override
    public FareInfoDTO getFare(Long addressId) {
        R r = memberFeignService.info(addressId);
        FareInfoDTO fareInfoVO = new FareInfoDTO();
        if (r != null) {
            MemberAddressVO memberAddressDTO =  r.getData("memberReceiveAddress",new TypeReference<MemberAddressVO>(){});
            String phone = memberAddressDTO.getPhone();
            String fare = phone.substring(phone.length()-1);
            fareInfoVO.setMemberAddressVO(memberAddressDTO);
            fareInfoVO.setFare(new BigDecimal(fare));
        }
        return fareInfoVO;
    }

    /**
     * 创建订单，验证令牌，验证价格，锁库存
     * @param command
     * @return
     */
    @Override
    @Transactional
    //@GlobalTransactional
    public SubmitOrderResponseVO submitOrder(SubmitOrderCommand command) {
        submitOrderCommandThreadLocal.set(command);
        SubmitOrderResponseVO responseVO = new SubmitOrderResponseVO();
        MemberDTO memberDTO = LoginInterceptor.memberDTOThreadLocal.get();
       //验证令牌 - 对比和删除必须是原子操作
        String orderTokenKey = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberDTO.getId();
        String orderTokenValue = command.getOrderTokenInput();
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList(orderTokenKey), orderTokenValue);
        responseVO.setCode(0);
        if ((result == null ? 0 : result) == 0) {
            //令牌认证失败
            responseVO.setCode(1);
        } else {
            OrderDTO order = createOrder();
            //保存订单
            saveOrder(order);
            //锁库存(skuId,skuName,number)
            WareSkuLockDTO wareSkuLockDTO = new WareSkuLockDTO();
            wareSkuLockDTO.setOrderSn(order.getOrder().getOrderSn());
            List<OrderItemDTO> collect = order.getOrderItemEntities().stream().map(item -> {
                OrderItemDTO dto = new OrderItemDTO();
                dto.setSkuId(item.getSkuId());
                dto.setItemCount(item.getSkuQuantity());
                dto.setTitle(item.getSkuName());
                return dto;
            }).collect(Collectors.toList());
            wareSkuLockDTO.setLockSkuInfo(collect);
            //锁库存
            // 这里发消息给库存服务
            R r = wmsFeignService.orderLockStock(wareSkuLockDTO);
            if (r.getCode() == 0) {
                //锁定成功
                responseVO.setOrder(order.getOrder());
                //订单创建成功发送消息给MQ
                rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
            } else {
                //锁定失败
                responseVO.setCode(2);
                String msg = (String) r.get("msg");
                throw new NoStockException(msg);
            }
        }
        return responseVO;
    }

    private void saveOrder(OrderDTO orderDTO) {
        OrderEntity order = orderDTO.getOrder();
        List<OrderItemEntity> orderItemEntities = orderDTO.getOrderItemEntities();
        this.save(order);
        orderItemService.saveBatch(orderItemEntities);
    }

    private OrderDTO createOrder() {
        OrderDTO orderDTO = new OrderDTO();
        //1、生产订单
        //创建订单号
        String orderSn = IdWorker.getTimeId();
        OrderEntity orderEntity = buildOrder(orderSn);
        //2、获取所有订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        //3、计算
        computeOtherInfo(orderEntity, orderItemEntities);
        orderDTO.setOrder(orderEntity);
        orderDTO.setOrderItemEntities(orderItemEntities);
        return orderDTO;
    }

    /**
     * 构建订单
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        SubmitOrderCommand submitOrderCommand = submitOrderCommandThreadLocal.get();
        MemberDTO memberDTO = LoginInterceptor.memberDTOThreadLocal.get();
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setBillContent("苹果手机订单");
        orderEntity.setMemberId(memberDTO.getId());
        orderEntity.setOrderSn(orderSn);
        orderEntity.setCreateTime(new Date());
        //实际支付价格
        orderEntity.setPayAmount(submitOrderCommand.getPayPriceInput());
        //获取收货地址
        FareInfoDTO fare = getFare(submitOrderCommand.getAddressIdInput());
        if (fare != null && fare.getMemberAddressVO() != null) {
            orderEntity.setReceiverCity(fare.getMemberAddressVO().getCity());
            orderEntity.setReceiverDetailAddress(fare.getMemberAddressVO().getDetailAddress());
            orderEntity.setReceiverName(fare.getMemberAddressVO().getName());
            orderEntity.setReceiverPhone(fare.getMemberAddressVO().getPhone());
            orderEntity.setReceiverPostCode(fare.getMemberAddressVO().getPostCode());
            orderEntity.setReceiverProvince(fare.getMemberAddressVO().getProvince());
            orderEntity.setReceiverRegion(fare.getMemberAddressVO().getRegion());
        }
        //设置订单状态
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        return orderEntity;
    }

    /**
     * 一个订单可能有多个商品
     * 构建所有订单项
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //获取所有订单项
        List<OrderItemDTO> checkedCartItems = cartFeignService.getCheckedCartItems();
        if (CollectionUtils.isNotEmpty(checkedCartItems)) {
            return checkedCartItems.stream().map(item -> {
                OrderItemEntity itemEntity = buildOrderItem(item);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
        }
        return Lists.newArrayList();
    }

    private OrderItemEntity buildOrderItem(OrderItemDTO dto) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1、订单信息：订单号
        //2、商品的spu信息
        SpuInfoDTO spuInfoDTO = productFeignService.getSpuInfoBySkuId(dto.getSkuId());
        if (spuInfoDTO != null) {
            orderItemEntity.setSpuId(spuInfoDTO.getId());
            orderItemEntity.setSpuBrand(spuInfoDTO.getBrandId().toString());
            orderItemEntity.setSpuName(spuInfoDTO.getSpuName());
            orderItemEntity.setCategoryId(spuInfoDTO.getCatalogId());
        }
        //3、商品的sku信息
        orderItemEntity.setSkuId(dto.getSkuId());
        orderItemEntity.setSkuName(dto.getTitle());
        orderItemEntity.setSkuPic(dto.getImage());
        String skuAttrs = StringUtils.collectionToDelimitedString(dto.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrs);
        orderItemEntity.setSkuQuantity(dto.getItemCount());
        //4、商品的优惠信息
        //5、积分信息
        orderItemEntity.setGiftGrowth(dto.getTotalPrice().intValue());
        orderItemEntity.setGiftIntegration(dto.getTotalPrice().intValue());
        //6、订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setRealAmount(dto.getTotalPrice());
        return orderItemEntity;
    }

    private void computeOtherInfo(OrderEntity orderEntity, List<OrderItemEntity> checkedCartItems){
        int giftGrowth = checkedCartItems.stream().mapToInt(OrderItemEntity::getGiftGrowth).sum();
        int giftIntegration = checkedCartItems.stream().mapToInt(OrderItemEntity::getGiftIntegration).sum();
        orderEntity.setGrowth(giftGrowth);
        orderEntity.setIntegration(giftIntegration);
        orderEntity.setDeleteStatus(0);
    }


    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        //关单之前一定要查寻当前订单的支付状态
        log.info("准备关闭订单:{}", entity.getOrderSn());
        String orderSn = entity.getOrderSn();
        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<OrderEntity>().eq("order_sn", orderSn);
        OrderEntity order = this.getOne(queryWrapper);
        if (order != null && order.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            UpdateWrapper<OrderEntity> updateWrapper = new UpdateWrapper<OrderEntity>().eq("order_sn", orderSn);
            order.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.update(order, updateWrapper);
            try {
                OrderInfoDTO orderInfoDTO = new OrderInfoDTO();
                BeanUtils.copyProperties(order, orderInfoDTO);
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderInfoDTO);
            } catch (Exception e) {

            }
        }
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberDTO memberDTO = LoginInterceptor.memberDTOThreadLocal.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                        .eq("member_id",memberDTO.getId())
                        .orderByDesc("create_time")
        );
        //遍历所有订单集合
        List<OrderEntity> orderEntityList = page.getRecords().stream().map(order -> {
            //根据订单号查询订单项里的数据
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                    .eq("order_sn", order.getOrderSn()));
            order.setOrderItemEntityList(orderItemEntities);
            return order;
        }).collect(Collectors.toList());
        System.out.println(JSON.toJSONString(orderEntityList));
        page.setRecords(orderEntityList);
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public String handleAliPayedResult(PayAsyncVo asyncVo) throws ParseException {
        //1,保存交易流水
        log.info("订单修改中...{}", JSON.toJSONString(asyncVo));
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(asyncVo.getTrade_no());
        paymentInfoEntity.setOrderSn(asyncVo.getOut_trade_no());
        paymentInfoEntity.setPaymentStatus(asyncVo.getTrade_status());
        paymentInfoEntity.setTotalAmount(new BigDecimal(asyncVo.getTotal_amount()));
        paymentInfoEntity.setCreateTime(new Date());
        paymentInfoEntity.setCallbackTime(DateUtils.parseDateStrictly(asyncVo.getNotify_time(),"yyyy-MM-dd HH:mm:ss"));
        paymentInfoService.save(paymentInfoEntity);
        String tradeStatus = asyncVo.getTrade_status();
        if (Objects.deepEquals(tradeStatus,"TRADE_SUCCESS") || Objects.deepEquals(tradeStatus,"TRADE_FINISHED")) {
            String outTradeNo = asyncVo.getOut_trade_no();
            //2,更改订单状态
            orderDao.updateOrderStatus(outTradeNo, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }
}